#!/usr/bin/python
# coding=utf-8
import random, sys, logging, time, traceback
from datetime import date
from flask import Flask, request, json, jsonify, abort, make_response
import sys, datetime, json, logging, os
import pandas as pd
import numpy as np
from scipy import fftpack
from Smooth_funcs import Smooth
from scipy.signal import find_peaks, savgol_filter
import time
import requests
from get_iot_data2 import GetIotData
from function_all import (
    add_windows,
    FFT_spectrogram,
    ButterworthFiltering,
    getXampl,
    hilbert_envelop,
    rms_feature,
)

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False

profile = (sys.argv[1].split("=", 1)[-1]) if len(sys.argv) > 1 else 'dev'


@app.route('/api-model/get_info.sdo', methods=["GET", "POST"])
def test_index_1():
    response_dict = {'message': 'success---hi--prm-server'}
    return json.dumps(response_dict)


@app.route('/api-model/', methods=["GET", "POST"])
def test_index_0():
    response_dict = {'message': 'success---hi--model-server'}
    return json.dumps(response_dict)


@app.route('/api-model/request_picture.sdo', methods=["GET", "POST"])
def request_model():
    content = dict()
    response_dict = dict()
    conclusion = ''
    advice = ''
    top = list()
    frequencyTop = list()
    diagnoseList = list()
    imbalance_rate = ''
    centering_rate1 = ''
    centering_rate2 = ''
    bearing_rate = ''
    songdong_rate = ''
    rec_create_time = ''
    body_dict = None
    if request.method == 'POST':
        try:
            try:
                request_json_text = request.get_data()
                body_dict = json.loads(request_json_text.decode('utf-8'))
            except Exception as e:
                body_dict = request.form.to_dict()
                # NOTE below is the pseudo code of post data fetching
                # postdata = request.form['id']
                # file = request.files['file']
        except Exception as e:
            body_dict = None
            traceback.print_exc()
    else:
        body_dict = request.args.to_dict(flat=True)

    #
    if body_dict is not None:
        try:
            code, msg, content, top, frequencyTop, rec_create_time, conclusion, advice, diagnoseList, imbalance_rate, centering_rate1, centering_rate2, bearing_rate, songdong_rate= run_model_job(p_body_dict=body_dict)
        except Exception as e:
            code = -100
            msg = f'run_model_job_failed---with--{str(body_dict)}--{str(e)}'

    else:
        code = -200
        msg = 'invalid_http_request_parameters'

    response_dict['code'] = code
    response_dict['message'] = msg
    response_dict['rec_create_time'] = rec_create_time
    response_dict['top'] = top
    response_dict['frequencyTop'] = frequencyTop
    response_dict['content'] = content
    response_dict['rec_create_time'] = rec_create_time
    response_dict['conclusion'] = conclusion
    response_dict['advice'] = advice
    response_dict['diagnoseList'] = diagnoseList
    response_dict['imbalance_rate'] = imbalance_rate
    response_dict['centering_rate1'] = centering_rate1
    response_dict['centering_rate2'] = centering_rate2
    response_dict['bearing_rate'] = bearing_rate
    response_dict['songdong_rate'] = songdong_rate
    # return json.dumps(response_dict)
    return bytes(json.dumps(response_dict), 'utf-8')
def run_model_job(p_body_dict):
    """

    """
    #程序开始
    content = dict()
    top = list()
    frequencyTop = list()
    diagnoseList = list()
    imbalance_rate = ''
    centering_rate1 = ''
    centering_rate2 = ''
    bearing_rate = ''
    songdong_rate = ''
    rec_create_time = ''
    conclusion = ''
    advice = ''

    row_data = p_body_dict
    tag = row_data['tag']
    now_time = row_data['time']
    timeMark = row_data['timeMark']
    direction = row_data['direction']
    couplingType = row_data['couplingType']
    motor = row_data['motor']
    motorAllow = row_data['motorAllow']
    picType = row_data['picType']
    bpfo = row_data['bpfo']
    bpfi = row_data['bpfi']
    bsf = row_data['bsf']
    fif = row_data['fif']
    RMStagList = row_data['RMStagList']
    majorCode = row_data['majorCode']
    if RMStagList != '':
        RMStagList = eval(RMStagList)
    else:
        RMStagList = []
    if majorCode == 'EM':
        judge_value = 2.3
    elif majorCode == 'FM':
        judge_value = 2.8
    elif majorCode == 'MT':
        judge_value = 1.8
    elif majorCode == 'MI':
        judge_value = 2.8
    else:
        judge_value = 2.3
    if motorAllow != '':
        motorAllow = float(motorAllow)
    if bpfo != '':
        bpfo = float(bpfo)
    if bpfi != '':
        bpfi = float(bpfi)
    if bsf != '':
        bsf = float(bsf)
    if fif != '':
        fif = float(fif)
    if motor != '':
        motor = float(motor)
        baseFrequency = motor / 60
    else:
        baseFrequency = 0
    if picType == 'all' or picType == 'frequency':
        topMin = row_data['topMin']
        if topMin != '':
            topMinF = float(topMin)
        else:
            topMinF = 0

        topMax = row_data['topMax']
        if topMax != '':
            topMaxF = float(topMax)
            topMaxF = topMaxF * baseFrequency
        else:
            topMaxF = 1000000000000

        topCount = row_data['topCount']
        if topCount != '':
            topCountF = int(topCount)
        else:
            topCountF = 0

        frequencyTop = row_data['frequencyTop']
        if frequencyTop != '':
            frequencyTopF = '"' + frequencyTop + '"'
            frequencyTopF = frequencyTopF.replace(',', '\",\"')
            frequencyTopF = eval(frequencyTopF)
            listF = list(frequencyTopF)
        else:
            listF = list()

    path = tag
    flag = int(timeMark) - 1
    # run_status, msg, rst = GetIotData.get_iot_signal(path, now_time, flag)
    run_status, msg, rst = GetIotData.get_iot_signal_newest_nhs(path, now_time, flag)
    if run_status == True:
        hz = rst['hz']
        cl = rst['cl']
        values = rst['values']
        start_time = rst['start_time']
        # end_time = rst['end_time']
        start_timestamp = int(start_time) / 1000000000
        stime = datetime.datetime.fromtimestamp(start_timestamp)
        stime_out = stime.strftime("%Y/%m/%d %H:%M:%S.%f")
        # rec_create_time = str(stime_out)
        rec_create_time = stime_out[:-3]
        # end_timestamp = int(end_time) / 1000000000
        # etime = datetime.datetime.fromtimestamp(end_timestamp)
        # etime_out = etime.strftime("%Y/%m/%d %H:%M:%S.%f")
        # rec_create_time = str(stime_out)+'-'+str(etime_out)
        rawData = values
        fs = float(hz)
        raw_data = np.array(rawData)
        # 去直流
        data_mean = sum(raw_data) / len(raw_data)
        raw_data -= data_mean
        data = np.asarray(raw_data)
        x_axis, y_axis = FFT_spectrogram(data, fs)
        # if motor != '':
        #     motor = float(motor)
        # else:
        #     max_xAmpl = np.max(y_axis)
        #     index = np.where(y_axis == max_xAmpl)
        #     motor = x_axis[index][0] * 60
        max_x_axis = np.max(x_axis)
        max_y_axis = np.max(y_axis)
        if motor != '' and 0 < float(motor) / 6 <= max_x_axis:
            motor = float(motor)
        else:
            max_xAmpl = np.max(y_axis)
            index = np.where(y_axis == max_xAmpl)
            rotate0 = x_axis[index][0] * 60
            time_range = len(data) / fs
            rotate1 = cal_rotate(time_range, data)
            if rotate0 / 6 <= min(500, max_x_axis) and rotate1 / 6 <= min(500, max_x_axis):
                motor = rotate0
            elif rotate0 / 6 > max(500, max_x_axis) and rotate1 / 6 > max(500, max_x_axis):
                motor = 980
            else:
                motor = min(rotate0, rotate1)
        diagnose_type = 1
        if len(RMStagList) > 0:
            iot_value_list = []
            for iot_tag_tmp in RMStagList:
                # iot_tag = "root.BGTA.BGTAIOBC00.EMFN_GWV_01.SNR.R00500.C01.V_VV_VEL"
                split_path_tag = iot_tag_tmp.rsplit('.', 1)
                iot_path = split_path_tag[0]
                iot_tag = split_path_tag[1]
                iot_now_time = int(start_time)
                iot_run_status, iot_msg, iot_rst = GetIotData.get_iot_value_newest_nhs(iot_path, iot_tag, iot_now_time)
                if iot_run_status == True:
                    iot_value = iot_rst['value']
                    iot_value_list.append(iot_value)
            # iot_value_list.append(3)
            if len(iot_value_list) > 0:
                judge_num = 0
                #判断个数
                for iot_value_tmp in iot_value_list:
                    if iot_value_tmp > judge_value:
                        judge_num += 1
                        #如果RMS超过阈值，判断个数加一
                #如果任意一个RMS超过阈值，则判断个数大于0，此时判断最大幅值是否超过1
                if judge_num > 0 and max_y_axis > 1:
                    diagnose_type = 1
                    #diagnose_type为1，需要诊断
                else:
                    diagnose_type = 0

        if (direction == 'HVIB' or direction == 'VVIB' or direction == 'AXVIB') and diagnose_type == 1:
            conclusion = ''
            advice = ''
            xampl,if_df_kong = getXampl2(x_axis, y_axis, motor, motorAllow)
            if if_df_kong == 0:
                diagnoseList.append({'axisX': 1,
                                     'axisY': float(xampl["1xAmpl"])})
                diagnoseList.append({'axisX': 2,
                                     'axisY': float(xampl["2xAmpl"])})
                diagnoseList.append({'axisX': 3,
                                     'axisY': float(xampl["3xAmpl"])})
                diagnoseList.append({'axisX': 4,
                                     'axisY': float(xampl["4xAmpl"])})
                diagnoseList.append({'axisX': 5,
                                     'axisY': float(xampl["5xAmpl"])})
                diagnoseList.append({'axisX': 6,
                                     'axisY': float(xampl["6xAmpl"])})
                diagnoseList.append({'axisX': 7,
                                     'axisY': float(xampl["7xAmpl"])})
                diagnoseList.append({'axisX': 8,
                                     'axisY': float(xampl["8xAmpl"])})
                diagnoseList.append({'axisX': 9,
                                     'axisY': float(xampl["9xAmpl"])})
                diagnoseList.append({'axisX': 10,
                                     'axisY': float(xampl["10xAmpl"])})

                # 不平衡
                imbalance_rate = float(xampl["1xAmpl"] / xampl.sum(axis=1))
                if couplingType != '膜片联轴器':
                    if imbalance_rate > 0.7:
                        conclusion += '转子或轴系存在不平衡情况'
                        advice += '调整转子平衡状态，排除轴系不平衡情况'
                    else:
                        conclusion += ''
                        advice += ''
                else:
                    if imbalance_rate > 0.6:
                        conclusion += '转子或轴系存在不平衡情况'
                        advice += '调整转子平衡状态，排除轴系不平衡情况'
                    else:
                        conclusion += ''
                        advice += ''
                # 不对中
                centering_rate1 = float((xampl["1xAmpl"] + xampl["2xAmpl"]) / xampl.sum(axis=1))
                centering_rate2 = float(xampl["2xAmpl"] / xampl["1xAmpl"])
                # if centering_rate1 > 0.6 or centering_rate2 > 0.5:
                if (centering_rate1 > 0.7 and centering_rate1 <= 0.8 and centering_rate2 <= 0.6) or (centering_rate2 > 0.5 and centering_rate2 <= 0.6 and centering_rate1 <= 0.8):
                    if len(conclusion) == 0:
                        conclusion += '设备对中有偏差'
                        advice += '检查联轴器状态及设备对中情况'
                    else:
                        conclusion += '；设备对中有偏差'
                        advice += '；检查联轴器状态及设备对中情况'
                elif centering_rate1 > 0.8 or centering_rate2 > 0.6:
                    if len(conclusion) == 0:
                        conclusion += '设备对中不良'
                        advice += '联轴器检查并重新找正'
                    else:
                        conclusion += '；设备对中不良'
                        advice += '；联轴器检查并重新找正'
                else:
                    conclusion += ''
                    advice += ''
                # print(len(conclusion))

                # 轴承故障
                if bpfi != '' and bpfo != '' and bsf != '' and fif != '':
                    return_df = pd.DataFrame(
                        columns=['name', 'ampl', 'value'])
                    for i in range(1, 4):
                        tmp_dict = {}
                        tmp_dict['name'] = 'bpfi'
                        tmp_dict['ampl'] = i
                        ratio = x_axis[1] - x_axis[0]
                        energy_range_1 = int((motor / 60 * bpfi * i * (1 - motorAllow)) / ratio)
                        energy_range_2 = int((motor / 60 * bpfi * i * (1 + motorAllow)) / ratio)
                        energy = max(y_axis[energy_range_1:energy_range_2], default=0)
                        tmp_dict['value'] = round(energy, 4)
                        new_row = pd.Series(tmp_dict)
                        return_df = return_df.append(new_row, ignore_index=True)
                    for i in range(1, 4):
                        tmp_dict = {}
                        tmp_dict['name'] = 'bpfo'
                        tmp_dict['ampl'] = i
                        ratio = x_axis[1] - x_axis[0]
                        energy_range_1 = int((motor / 60 * bpfo * i * (1 - motorAllow)) / ratio)
                        energy_range_2 = int((motor / 60 * bpfo * i * (1 + motorAllow)) / ratio)
                        energy = max(y_axis[energy_range_1:energy_range_2], default=0)
                        tmp_dict['value'] = round(energy, 4)
                        new_row = pd.Series(tmp_dict)
                        return_df = return_df.append(new_row, ignore_index=True)
                    for i in range(1, 4):
                        tmp_dict = {}
                        tmp_dict['name'] = 'bsf'
                        tmp_dict['ampl'] = i
                        ratio = x_axis[1] - x_axis[0]
                        energy_range_1 = int((motor / 60 * bsf * i * (1 - motorAllow)) / ratio)
                        energy_range_2 = int((motor / 60 * bsf * i * (1 + motorAllow)) / ratio)
                        energy = max(y_axis[energy_range_1:energy_range_2], default=0)
                        tmp_dict['value'] = round(energy, 4)
                        new_row = pd.Series(tmp_dict)
                        return_df = return_df.append(new_row, ignore_index=True)
                    for i in range(1, 4):
                        tmp_dict = {}
                        tmp_dict['name'] = 'fif'
                        tmp_dict['ampl'] = i
                        ratio = x_axis[1] - x_axis[0]
                        energy_range_1 = int((motor / 60 * fif * i * (1 - motorAllow)) / ratio)
                        energy_range_2 = int((motor / 60 * fif * i * (1 + motorAllow)) / ratio)
                        energy = max(y_axis[energy_range_1:energy_range_2], default=0)
                        tmp_dict['value'] = round(energy, 4)
                        new_row = pd.Series(tmp_dict)
                        return_df = return_df.append(new_row, ignore_index=True)
                    sum_12 = return_df['value'].sum()
                    bearing_rate = sum_12 / float(xampl["1xAmpl"])
                    return_df1 = return_df[return_df['name'] == 'bpfi']
                    return_df1 = return_df1.reset_index(drop=True)
                    sum_1 = return_df1['value'].sum()
                    return_df2 = return_df[return_df['name'] == 'bpfo']
                    return_df2 = return_df2.reset_index(drop=True)
                    sum_2 = return_df2['value'].sum()
                    return_df3 = return_df[return_df['name'] == 'bsf']
                    return_df3 = return_df3.reset_index(drop=True)
                    sum_3 = return_df3['value'].sum()
                    return_df4 = return_df[return_df['name'] == 'fif']
                    return_df4 = return_df4.reset_index(drop=True)
                    sum_4 = return_df4['value'].sum()
                    if bearing_rate > 0.6 and bearing_rate <= 0.7:
                        if len(conclusion) == 0:
                            conclusion += '轴承存在早期磨损及润滑不良'
                            advice += '增加润滑，跟踪轴承振动及声音情况'
                        else:
                            conclusion += '；轴承存在早期磨损及润滑不良'
                            advice += '；增加润滑，跟踪轴承振动及声音情况'
                        if sum_1 > 0.4 * sum_12:
                            conclusion += '，并跟踪轴承内圈运行情况'
                        if sum_2 > 0.4 * sum_12:
                            conclusion += '，并跟踪轴承外圈运行情况'
                        if sum_3 > 0.4 * sum_12:
                            conclusion += '，并跟踪轴承滚动体运行情况'
                        if sum_4 > 0.4 * sum_12:
                            conclusion += '，并跟踪轴承保持架运行情况'
                    elif bearing_rate > 0.7:
                        if len(conclusion) == 0:
                            conclusion += '轴承存在异常磨损'
                            advice += '增加润滑，调整轴承装配或者更换轴承'
                        else:
                            conclusion += '；轴承存在异常磨损'
                            advice += '；增加润滑，调整轴承装配或者更换轴承'
                        if sum_1 > 0.5 * sum_12:
                            conclusion += '，择机检查轴承内圈情况'
                        if sum_2 > 0.5 * sum_12:
                            conclusion += '，择机检查轴承外圈情况'
                        if sum_3 > 0.5 * sum_12:
                            conclusion += '，择机检查轴承滚动体情况'
                        if sum_4 > 0.5 * sum_12:
                            conclusion += '，择机检查轴承保持架情况'
                    else:
                        conclusion += ''
                        advice += ''
                # print(len(conclusion))
                # 松动
                songdong_rate = float((xampl["3xAmpl"] + xampl["4xAmpl"] + xampl["5xAmpl"] + xampl["6xAmpl"] + xampl["7xAmpl"] + xampl["8xAmpl"] + xampl["9xAmpl"] + xampl["10xAmpl"]) / xampl.sum(axis=1))
                if songdong_rate > 0.5:
                    if len(conclusion) == 0:
                        conclusion += '地脚不平或螺栓存在松动情况'
                        advice += '检查地脚水平，轴承座及设备地脚螺栓紧固情况'
                    else:
                        conclusion += '；地脚不平或螺栓存在松动情况'
                        advice += '；检查地脚水平，轴承座及设备地脚螺栓紧固情况'
                else:
                    conclusion += ''
                    advice += ''
        elif diagnose_type == 0:
            conclusion = '状态良好'
            advice = ''
        else:
            conclusion = ''
            advice = ''


        signal_info_hz =hz
        signal_info_output = cl
        signal_value = values
        content = dict()
        #转换作图数据开始

        if picType == 'all':
            df_time = getcoordinate(p_picType='time',
                                    p_signal_info_hz=signal_info_hz, p_signal_info_output=signal_info_output,
                                    p_signal_value=signal_value)
            df_frequency = getcoordinate(p_picType='frequency',
                                         p_signal_info_hz=signal_info_hz, p_signal_info_output=signal_info_output,
                                         p_signal_value=signal_value)
            df_envelope = getcoordinate(p_picType='envelope',
                                        p_signal_info_hz=signal_info_hz, p_signal_info_output=signal_info_output,
                                        p_signal_value=signal_value)

            mydata_time = df_time.to_json(orient='records', force_ascii=False)
            mydata_time = eval(mydata_time)
            data_time = mydata_time
            content['data_time'] = data_time
    ########20231116第一个：以前返回数据时是按照倍频（转速/60）的数据做的最大七倍频的数据量，现在不做这个倍频的限制了
            dfF = df_frequency
    ###################################################################################
            dfF = dfF.reset_index(drop=True)
            mydata_frequency = dfF.to_json(orient='records', force_ascii=False)
            mydata_frequency = eval(mydata_frequency)
            data_frequency = mydata_frequency
            content['data_frequency'] = data_frequency

            mydata_envelope = df_envelope.to_json(orient='records', force_ascii=False)
            mydata_envelope = eval(mydata_envelope)

            data_envelope = mydata_envelope
            content['data_envelope'] = data_envelope

            top = list()
            frequencyTop = list()
            df = df_frequency
            #####################现在如果没有转速的话，就直接把时域、频域、包络的原始数据返回来，不需要计算，1-5倍频的这个倍频的峰值了
            if motor != '':
                if topMin != '' and topMax != '':
                    df_top = df[(df['axisX'] >= topMinF) & (df['axisX'] <= topMaxF)]
                elif topMin != '' and topMax == '':
                    df_top = df[(df['axisX'] >= topMinF)]
                elif topMin == '' and topMax != '':
                    df_top = df[(df['axisX'] <= topMaxF)]
                elif topMin == '' and topMax == '':
                    df_top = df
                if topCount != '':
                    df_top = df_top.sort_values(['axisY'], ascending=False)
                    df_top = df_top.reset_index(drop=True)
                    n = topCountF
                    df_top_n = df_top.iloc[:n]
                    # print(df_top_n)
                    top_data = df_top_n.to_json(orient='records', force_ascii=False)
                    top_data = eval(top_data)
                    top = top_data
                else:
                    top = list()


                if frequencyTop != '':
                    bq_min = motor / 60 * (1 - motorAllow)
                    bq_max = motor / 60 * (1 + motorAllow)
                    df_bq1 = df[(df['axisX'] >= bq_min) & (df['axisX'] <= bq_max)]
                    success = df_bq1.empty is False
                    if success is True:
                        df_bq1 = df_bq1.sort_values(['axisY'], ascending=False)
                        df_bq1 = df_bq1.reset_index(drop=True)
                        bq1 = df_bq1.loc[0, 'axisX']
                        for i in range(len(listF)):
                            str_tmp = listF[i]
                            s = float(str_tmp)
                            bq_tmp = bq1 * s
                            df_bq_tmp = df[df['axisX'] == bq_tmp]
                            # print(df_bq_tmp)
                            df_bq_tmp = df_bq_tmp.reset_index(drop=True)
                            bq_tmp_energy = df_bq_tmp.loc[0, 'axisY']
                            frequencyTop.append({'axisX': bq_tmp,
                                                 'axisY': bq_tmp_energy})
                    else:
                        bq_min2 = motor / 60 * (1 - motorAllow) * 2
                        bq_max2 = motor / 60 * (1 + motorAllow) * 2
                        df_bq2 = df[(df['axisX'] >= bq_min2) & (df['axisX'] <= bq_max2)]
                        success = df_bq2.empty is False
                        if success is True:
                            df_bq2 = df_bq2.sort_values(['axisY'], ascending=False)
                            df_bq2 = df_bq2.reset_index(drop=True)
                            bq2 = df_bq2.loc[0, 'axisX']
                            bq2_energy = df_bq2.loc[0, 'axisY']
                            bq1 = bq2 / 2
                            ratio = df.loc[1, 'axisX'] - df.loc[0, 'axisX']
                            df_bq1 = df[(df['axisX'] >= bq1 - ratio) & (df['axisX'] <= bq1 + ratio)]
                            df_bq1 = df_bq1.sort_values(['axisY'], ascending=False)
                            df_bq1 = df_bq1.reset_index(drop=True)
                            bq1 = df_bq1.loc[0, 'axisX']
                            bq1_energy = df_bq1.loc[0, 'axisY']
                            # return_df["1xAmpl"] = [round(bq1_energy, 4)]
                            # return_df["2xAmpl"] = [round(bq2_energy, 4)]
                            for i in range(len(listF)):
                                str_tmp = listF[i]
                                s = float(str_tmp)
                                if s == 1:
                                    frequencyTop.append({'axisX': bq1,
                                                         'axisY': bq1_energy})
                                elif s == 2:
                                    frequencyTop.append({'axisX': bq2,
                                                         'axisY': bq2_energy})
                                else:
                                    bq_tmp = bq1 * s
                                    df_bq_tmp = df[(df['axisX'] >= bq_tmp - ratio) & (df['axisX'] <= bq_tmp + ratio)]
                                    df_bq_tmp = df_bq_tmp.sort_values(['axisY'], ascending=False)
                                    df_bq_tmp = df_bq_tmp.reset_index(drop=True)
                                    bq_tmp_energy = df_bq_tmp.loc[0, 'axisY']
                                    frequencyTop.append({'axisX': bq_tmp,
                                                         'axisY': bq_tmp_energy})
                        else:
                            bq_1 = motor / 60
                            for i in range(len(listF)):
                                str_tmp = listF[i]
                                s = float(str_tmp)
                                bq_tmp = bq_1 * s
                                frequencyTop.append({'axisX': bq_tmp,
                                                     'axisY': 0})


                else:
                    frequencyTop = list()




        else:
            df = getcoordinate(p_picType=picType,
                                               p_signal_info_hz=signal_info_hz, p_signal_info_output=signal_info_output,
                                               p_signal_value=signal_value)
            top = list()
            frequencyTop = list()
            if picType == 'frequency':
                if topMin != '' and topMax != '':
                    df_top = df[(df['axisX'] >= topMinF) & (df['axisX'] <= topMaxF)]
                elif topMin != '' and topMax == '':
                    df_top = df[(df['axisX'] >= topMinF)]
                elif topMin == '' and topMax != '':
                    df_top = df[(df['axisX'] <= topMaxF)]
                elif topMin == '' and topMax == '':
                    df_top = df
    ########20231116第一个：以前返回数据时是按照倍频（转速/60）的数据做的最大七倍频的数据量，现在不做这个倍频的限制了
                df = df
    ###################################################################################
                df = df.reset_index(drop=True)
    #####################现在如果没有转速的话，就直接把时域、频域、包络的原始数据返回来，不需要计算，1-5倍频的这个倍频的峰值了
                if motor != '':
                    if topCount != '':
                        df_top = df_top.sort_values(['axisY'], ascending=False)
                        df_top = df_top.reset_index(drop=True)
                        n = topCountF
                        df_top_n = df_top.iloc[:n]
                        top_data = df_top_n.to_json(orient='records', force_ascii=False)
                        top_data = eval(top_data)
                        top = top_data
                    else:
                        top = list()

                    if frequencyTop != '':
                        bq_min = motor / 60 * (1 - motorAllow)
                        bq_max = motor / 60 * (1 + motorAllow)
                        df_bq1 = df[(df['axisX'] >= bq_min) & (df['axisX'] <= bq_max)]
                        success = df_bq1.empty is False
                        if success is True:
                            df_bq1 = df_bq1.sort_values(['axisY'], ascending=False)
                            df_bq1 = df_bq1.reset_index(drop=True)
                            bq1 = df_bq1.loc[0, 'axisX']
                            for i in range(len(listF)):
                                str_tmp = listF[i]
                                s = float(str_tmp)
                                bq_tmp = bq1 * s
                                df_bq_tmp = df[df['axisX'] == bq_tmp]
                                df_bq_tmp = df_bq_tmp.reset_index(drop=True)
                                bq_tmp_energy = df_bq_tmp.loc[0, 'axisY']
                                frequencyTop.append({'axisX': bq_tmp,
                                                     'axisY': bq_tmp_energy})
                        else:
                            bq_min2 = motor / 60 * (1 - motorAllow) * 2
                            bq_max2 = motor / 60 * (1 + motorAllow) * 2
                            df_bq2 = df[(df['axisX'] >= bq_min2) & (df['axisX'] <= bq_max2)]
                            success = df_bq2.empty is False
                            if success is True:
                                df_bq2 = df_bq2.sort_values(['axisY'], ascending=False)
                                df_bq2 = df_bq2.reset_index(drop=True)
                                bq2 = df_bq2.loc[0, 'axisX']
                                bq2_energy = df_bq2.loc[0, 'axisY']
                                bq1 = bq2 / 2
                                ratio = df.loc[1, 'axisX'] - df.loc[0, 'axisX']
                                df_bq1 = df[(df['axisX'] >= bq1 - ratio) & (df['axisX'] <= bq1 + ratio)]
                                df_bq1 = df_bq1.sort_values(['axisY'], ascending=False)
                                df_bq1 = df_bq1.reset_index(drop=True)
                                bq1 = df_bq1.loc[0, 'axisX']
                                bq1_energy = df_bq1.loc[0, 'axisY']
                                # return_df["1xAmpl"] = [round(bq1_energy, 4)]
                                # return_df["2xAmpl"] = [round(bq2_energy, 4)]
                                for i in range(len(listF)):
                                    str_tmp = listF[i]
                                    s = float(str_tmp)
                                    if s == 1:
                                        frequencyTop.append({'axisX': bq1,
                                                             'axisY': bq1_energy})
                                    elif s == 2:
                                        frequencyTop.append({'axisX': bq2,
                                                             'axisY': bq2_energy})
                                    else:
                                        bq_tmp = bq1 * s
                                        df_bq_tmp = df[
                                            (df['axisX'] >= bq_tmp - ratio) & (df['axisX'] <= bq_tmp + ratio)]
                                        df_bq_tmp = df_bq_tmp.sort_values(['axisY'], ascending=False)
                                        df_bq_tmp = df_bq_tmp.reset_index(drop=True)
                                        bq_tmp_energy = df_bq_tmp.loc[0, 'axisY']
                                        frequencyTop.append({'axisX': bq_tmp,
                                                             'axisY': bq_tmp_energy})
                            else:
                                bq_1 = motor / 60
                                for i in range(len(listF)):
                                    str_tmp = listF[i]
                                    s = float(str_tmp)
                                    bq_tmp = bq_1 * s
                                    frequencyTop.append({'axisX': bq_tmp,
                                                         'axisY': 0})

                    else:
                        frequencyTop = list()





            mydate = df.to_json(orient='records', force_ascii=False)
            mydate = eval(mydate)
            data = mydate
            content['data'] = data


        code = 0
        msg = 'ok'
    else:
        code = -300
        msg = '未读取到数据'
        top = []
        frequencyTop = []
        content = {}
    return code, msg, content, top, frequencyTop, rec_create_time, conclusion, advice, diagnoseList, imbalance_rate, centering_rate1, centering_rate2, bearing_rate, songdong_rate

def getcoordinate(p_picType, p_signal_info_hz, p_signal_info_output, p_signal_value):
    # p_signal_value = eval(p_signal_value)

    x = [float(v) for v in p_signal_value]
    sampling_rate = p_signal_info_hz  # 取样频率(来自传感器说明书)
    fft_size = p_signal_info_output  # FFT处理的数据样本数
    xt = np.asarray(x)
    xt = xt - np.mean(xt)  # 去直流分量
    if p_picType == 'time':
        tstemp = np.linspace(0, int(1e6 / sampling_rate * fft_size), fft_size) / 1e3
        arr3 = np.vstack((tstemp, xt))
        arr3t = arr3.T
        df = pd.DataFrame(arr3t, columns=['axisX', 'axisY'])
    if p_picType == 'frequency':
        am = np.fft.fft(xt)  # 对希尔伯特变换后的at做fft变换获得幅值
        am = np.abs(am)  # 对幅值求绝对值（此时的绝对值很大）
        am = am / len(am) * 2
        am = am[0: int(len(am) / 2)]
        freq = np.fft.fftfreq(len(xt), d=1 / sampling_rate)  # 获取fft频率，此时包括正频率和负频率
        freq = freq[0:int(len(freq) / 2)]  # 获取正频率
        arr3 = np.vstack((freq, am))
        arr3t = arr3.T
        df = pd.DataFrame(arr3t, columns=['axisX', 'axisY'])

    if p_picType == 'envelope':
        ht = fftpack.hilbert(xt)
        at = np.sqrt(ht ** 2 + xt ** 2)  # at = sqrt(xt^2 + ht^2)
        sampling_rate = sampling_rate
        at = at - np.mean(at)  # 去直流分量
        am = np.fft.fft(at)  # 对希尔伯特变换后的at做fft变换获得幅值
        am = np.abs(am)  # 对幅值求绝对值（此时的绝对值很大）
        am = am / len(am) * 2
        am = am[0: int(len(am) / 2)]
        freq = np.fft.fftfreq(len(at), d=1 / sampling_rate)  # 获取fft频率，此时包括正频率和负频率
        freq = freq[0:int(len(freq) / 2)]  # 获取正频率
        arr3 = np.vstack((freq, am))
        arr3t = arr3.T
        df = pd.DataFrame(arr3t, columns=['axisX', 'axisY'])
    return df
def getXampl2(x_axis, y_axis, motor, motorAllow):
    return_df = pd.DataFrame()
    if_df_kong = 0
    arr3 = np.vstack((x_axis, y_axis))
    arr3t = arr3.T
    df = pd.DataFrame(arr3t, columns=['axisX', 'axisY'])
    bq_min = motor / 60 * (1 - motorAllow)
    bq_max = motor / 60 * (1 + motorAllow)
    df_bq1 = df[(df['axisX'] >= bq_min) & (df['axisX'] <= bq_max)]
    success = df_bq1.empty is False
    if success is True:
        df_bq1 = df_bq1.sort_values(['axisY'], ascending=False)
        df_bq1 = df_bq1.reset_index(drop=True)
        bq1 = df_bq1.loc[0, 'axisX']
        bq1_energy = df_bq1.loc[0, 'axisY']
        return_df["1xAmpl"] = [round(bq1_energy, 4)]
        for i in range(2, 11):
            bq_tmp = bq1 * i
            ratio = x_axis[1] - x_axis[0]
            df_bq_tmp = df[(df['axisX'] >= bq_tmp - ratio) & (df['axisX'] <= bq_tmp + ratio)]
            df_bq_tmp = df_bq_tmp.sort_values(['axisY'], ascending=False)
            df_bq_tmp = df_bq_tmp.reset_index(drop=True)
            bq_tmp_energy = df_bq_tmp.loc[0, 'axisY']
            # df_bq_tmp = df[df['axisX'] == bq_tmp]
            # df_bq_tmp = df_bq_tmp.reset_index(drop=True)
            # bq_tmp_energy = df_bq_tmp.loc[0, 'axisY']
            return_df[str(i) + "xAmpl"] = [round(bq_tmp_energy, 4)]
    else:
        bq_min2 = motor / 60 * (1 - motorAllow) * 2
        bq_max2 = motor / 60 * (1 + motorAllow) * 2
        df_bq2 = df[(df['axisX'] >= bq_min2) & (df['axisX'] <= bq_max2)]
        success = df_bq2.empty is False
        if success is True:
            df_bq2 = df_bq2.sort_values(['axisY'], ascending=False)
            df_bq2 = df_bq2.reset_index(drop=True)
            bq2 = df_bq2.loc[0, 'axisX']
            bq2_energy = df_bq2.loc[0, 'axisY']
            bq1 = bq2 / 2
            ratio = x_axis[1] - x_axis[0]
            df_bq1 = df[(df['axisX'] >= bq1 - ratio) & (df['axisX'] <= bq1 + ratio)]
            df_bq1 = df_bq1.sort_values(['axisY'], ascending=False)
            df_bq1 = df_bq1.reset_index(drop=True)
            bq1 = df_bq1.loc[0, 'axisX']
            bq1_energy = df_bq1.loc[0, 'axisY']
            return_df["1xAmpl"] = [round(bq1_energy, 4)]
            return_df["2xAmpl"] = [round(bq2_energy, 4)]
            for i in range(3, 11):
                bq_tmp = bq1 * i
                df_bq_tmp = df[(df['axisX'] >= bq_tmp - ratio) & (df['axisX'] <= bq_tmp + ratio)]
                df_bq_tmp = df_bq_tmp.sort_values(['axisY'], ascending=False)
                df_bq_tmp = df_bq_tmp.reset_index(drop=True)
                bq_tmp_energy = df_bq_tmp.loc[0, 'axisY']
                return_df[str(i) + "xAmpl"] = [round(bq_tmp_energy, 4)]

        else:
            if_df_kong = 1
    return return_df,if_df_kong
def cal_rotate(time_range, waveform):
    ct = len(waveform)
    t = np.linspace(0, time_range, ct)
    waveform_smooth1 = savgol_filter(waveform, window_length=31, polyorder=3)
    waveform_smooth = Smooth.smooth3(waveform_smooth1, int(ct * 0.01))
    # peaks = peakutils.indexes(waveform_smooth, thres=0.5)
    peaks, _ = find_peaks(waveform_smooth)  # 检测波峰

    # plt.figure(figsize=(15, 4))
    # plt.plot(t, waveform)
    # plt.plot(t, waveform_smooth)
    # plt.plot(t[peaks], waveform_smooth[peaks], "x", label="Peaks", color='red')
    # plt.xlabel("Time")
    # plt.ylabel("Amplitude")
    # plt.legend()
    # plt.show()

    time_diff = np.diff(t[peaks])
    time_diff_max = np.max(time_diff)
    rotate_max = 1 / time_diff_max * 60

    return rotate_max
if __name__ == '__main__':

    app.run(host='0.0.0.0', port=7079)
